<?php

namespace app\api\service;

use app\common\model\user\User as UserModel;
use tmcore\base\BaseService;
use tmcore\exceptions\JwtException;
use tmcore\services\JwtTokenService;

class ApiTokenService extends BaseService
{
    protected static string $token_type = 'api';

    protected static int $expire_duration = 3600 * 12;

    protected static bool $is_expire_extension = false;

    /**
     * 通过token获取用户信息
     * @param $token
     * @return array|bool
     * @throws JwtException
     */
    public static function getUserInfo($token)
    {
        $res = JwtTokenService::parseToken($token, self::$is_expire_extension);
        if($res) {
            if($res['type'] != self::$token_type) return self::setError('token类型有误');
            $user = UserModel::where(['id' => $res['id']])->findOrEmpty();

            return [
                'id' => $user->id,
                'account' => $user->account,
                'mobile' => $user->mobile,
                'nickname' => $user->nickname,
                'avatar' => $user->avatar,
                'token' => $token,
                'channel' => $res['params']['channel']??'',
                'expire_time' => $res['params']['exp']??'',
            ];
        }
    }

    /**
     * 设置用户token
     * @param int $id
     * @param integer $channel
     * @param boolean $multipointLogin
     * @return array|bool
     * @throws JwtException
     */
    public static function setToken($id, $channel, $multipointLogin)
    {
        $res = JwtTokenService::createToken($id, self::$token_type, self::$expire_duration, ['channel' => $channel], $multipointLogin);
        return ['token' => $res['token'], 'expire' => self::$expire_duration];
    }

    /**
     * 清空 token
     * @param $id
     * @param $token
     * @return bool
     */
    public static function clearToken($id, $token = '')
    {
        return JwtTokenService::clearToken($id, self::$token_type, $token);
    }
}